<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>成远生产管控平台 - 后台管理系统</title>
    <link rel="stylesheet" href="../layui/css/layui.css">
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <style>
        :root {
            --primary-color: #009688;
            --secondary-color: #2F4056;
            --accent-color: #1E9FFF;
            --light-gray: #f5f7fa;
            --dark-gray: #393D49;
            --border-radius: 8px;
            --box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif;
            font-size: 14px;
            color: #333;
            background-color: #f0f2f5;
            background-image: url('../images/bg.jpg');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }

        /* 全局组件样式 */
        .layui-table th,
        .layui-form-label,
        .layui-btn {
            font-weight: 500;
        }

        .layui-table td {
            font-size: 13px;
        }

        .layui-btn {
            border-radius: var(--border-radius);
            transition: all 0.3s ease;
        }

        .layui-btn-primary:hover {
            border-color: var(--primary-color);
            color: var(--primary-color);
        }

        .layui-form-select dl dd.layui-this {
            background-color: var(--primary-color);
        }

        .layui-form-checked[lay-skin="primary"] i {
            border-color: var(--primary-color);
            background-color: var(--primary-color);
        }

        .layui-tab-title li {
            font-weight: 500;
        }

        .layui-tab-title .layui-this {
            color: var(--primary-color);
        }

        .layui-tab-title .layui-this:after {
            border-bottom: 2px solid var(--primary-color);
        }

        /* 页面结构样式 */
        .header-container {
            background-color: #ffffff;
            padding: 15px 30px;
            box-shadow: var(--box-shadow);
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .header-left {
            display: flex;
            align-items: center;
        }

        .header-logo {
            display: flex;
            align-items: center;
            margin-right: 20px;
            padding-right: 20px;
            border-right: 1px solid #eee;
        }

        .header-logo i {
            font-size: 24px;
            color: var(--primary-color);
            margin-right: 10px;
        }

        .header-title {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
        }

        .header-info {
            color: #666;
        }

        .header-right {
            display: flex;
            align-items: center;
        }

        .user-info {
            display: flex;
            align-items: center;
            margin-right: 20px;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: var(--primary-color);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
        }

        .logout-btn {
            background-color: #ff5722;
            color: white;
        }

        .logout-btn:hover {
            background-color: #d84a1d;
        }

        .layui-layout-admin {
            margin: 20px;
            border-radius: var(--border-radius);
            overflow: hidden;
            box-shadow: var(--box-shadow);
            background-color: rgba(255, 255, 255, 0.95);
        }

        .layui-side {
            width: 220px !important;
            background-color: var(--secondary-color);
        }

        .layui-body {
            padding: 20px;
            overflow: auto;
        }

        /* 导航菜单样式 */
        .layui-nav-tree {
            width: 220px;
        }

        .layui-nav-tree .layui-nav-item {
            margin: 0;
        }

        .layui-nav-tree .layui-nav-item a {
            padding-left: 25px;
            height: 50px;
            line-height: 50px;
            transition: all 0.3s ease;
        }

        .layui-nav-tree .layui-nav-item a:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .layui-nav-tree .layui-nav-item.layui-this {
            background-color: var(--primary-color);
        }

        .layui-nav-tree .layui-nav-item.layui-this a:hover {
            background-color: var(--primary-color);
        }

        .layui-nav-tree .layui-nav-item i {
            margin-right: 10px;
        }

        /* 内容区域样式 */
        .content-container {
            background-color: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            padding: 20px;
            margin-bottom: 20px;
        }

        .section-title {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 20px;
            color: var(--secondary-color);
            display: flex;
            align-items: center;
        }

        .section-title i {
            margin-right: 10px;
            color: var(--primary-color);
        }

        /* 表格样式优化 */
        .layui-table {
            border-radius: var(--border-radius);
            overflow: hidden;
        }

        .layui-table thead tr {
            background-color: #f8f9fa;
        }

        .layui-table th {
            font-weight: 600;
            color: var(--secondary-color);
        }

        .layui-table tbody tr:hover {
            background-color: #f5f8ff;
        }

        .table-action-btn {
            height: 28px;
            line-height: 28px;
            padding: 0 8px;
            font-size: 12px;
            margin-right: 5px;
        }

        /* 查询表单样式 */
        .query-form {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            padding: 20px;
            background-color: #f8f9fa;
            border-radius: var(--border-radius);
            margin-bottom: 20px;
        }

        .query-form-item {
            display: flex;
            align-items: center;
            margin-bottom: 0;
        }

        .query-form-label {
            width: auto;
            padding-right: 10px;
            font-weight: 500;
            color: var(--secondary-color);
        }

        .query-form-input {
            width: 180px;
        }

        .query-form-checkbox {
            margin-left: 10px;
        }

        .query-form-actions {
            display: flex;
            gap: 10px;
            margin-left: auto;
        }

        /* 统计信息样式 */
        .statistics-container {
            padding: 15px 20px;
            background-color: #f0f2f5;
            border-radius: var(--border-radius);
            margin-top: 20px;
            font-weight: 500;
            color: var(--secondary-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .statistics-item {
            display: flex;
            align-items: center;
        }

        .statistics-item i {
            margin-right: 8px;
            color: var(--primary-color);
        }

        .statistics-value {
            font-weight: 600;
            color: #ff5722;
            margin-left: 5px;
        }

        /* 响应式设计 */
        @media screen and (max-width: 1200px) {
            .query-form {
                flex-direction: column;
                gap: 10px;
            }

            .query-form-item {
                width: 100%;
            }

            .query-form-input {
                width: 100%;
            }

            .query-form-actions {
                margin-left: 0;
                width: 100%;
            }
        }

        @media screen and (max-width: 768px) {
            .header-container {
                flex-direction: column;
                padding: 15px;
            }

            .header-left, .header-right {
                width: 100%;
                justify-content: center;
            }

            .header-logo {
                border-right: none;
                margin-right: 0;
                padding-right: 0;
                margin-bottom: 10px;
            }

            .user-info {
                margin-right: 0;
                margin-bottom: 10px;
            }

            .layui-side {
                display: none;
            }

            .layui-body {
                left: 0 !important;
            }
        }
    </style>
</head>
<body>
<!-- 顶部导航栏 -->
<div class="header-container">
    <div class="header-left">
        <div class="header-logo">
            <i class="fa fa-cogs"></i>
            <h3 class="header-title">成远生产管控平台</h3>
        </div>
        <div class="header-info">
            <p style="margin: 0;">欢迎您，<span id="usernameDisplay"></span>！</p>
            <p style="margin: 0;">当前时间：<span id="currentTime"></span></p>
        </div>
    </div>
    <div class="header-right">
        <div class="user-info">
            <div class="user-avatar"><i class="fa fa-user"></i></div>
            <span id="usernameDisplayMobile"></span>
        </div>
        <button class="layui-btn logout-btn" id="logoutBtn">
            <i class="fa fa-sign-out"></i> 退出系统
        </button>
    </div>
</div>

<div class="layui-layout layui-layout-admin">
    <!-- 左侧导航栏 -->
    <div class="layui-side">
        <div class="layui-side-scroll">
            <ul class="layui-nav layui-nav-tree" lay-filter="adminNav">
                <!-- 用户权限管理 -->
                <li class="layui-nav-item" data-tab="user">
                    <a href="javascript:;">
                        <i class="fa fa-users"></i>
                        <span>用户权限管理</span>
                    </a>
                </li>
                <!-- 数据查询 -->
                <li class="layui-nav-item" data-tab="query">
                    <a href="javascript:;">
                        <i class="fa fa-search"></i>
                        <span>数据查询</span>
                    </a>
                </li>
            </ul>
        </div>
    </div>

    <!-- 内容区域 -->
    <div class="layui-body">
        <div class="layui-tab" lay-filter="adminTabs" lay-allowclose="false">
            <ul class="layui-tab-title">
                <li class="layui-this" lay-id="user">用户管理</li>
                <li lay-id="query">数据查询</li>
            </ul>

            <div class="layui-tab-content">
                <!-- 用户管理 -->
                <div class="layui-tab-item layui-show">
                    <div class="content-container">
                        <div class="section-title">
                            <i class="fa fa-users"></i>
                            用户管理
                        </div>
                        <div class="layui-btn-container">
                            <button class="layui-btn layui-btn-primary" id="addUserBtn">
                                <i class="fa fa-plus"></i> 添加用户
                            </button>
                        </div>
                        <table id="userTable" lay-filter="userTable"></table>
                    </div>
                </div>

                <!-- 数据查询 -->
                <div class="layui-tab-item">
                    <div class="content-container">
                        <div class="section-title">
                            <i class="fa fa-search"></i>
                            数据查询
                        </div>

                        <div class="query-form">
                            <div class="query-form-item">
                                <label class="query-form-label">门岗</label>
                                <div class="layui-input-inline query-form-input">
                                    <select name="gate" lay-verify="gate">
                                        <option value="">请选择</option>
                                        <option value="门牌1">门牌1</option>
                                        <option value="门牌2">门牌2</option>
                                    </select>
                                </div>
                                <div class="layui-form-mid query-form-checkbox">
                                    <input type="checkbox" name="useGate" title="使用门岗查询" data-target="gate">
                                </div>
                            </div>

                            <div class="query-form-item">
                                <label class="query-form-label">车牌号</label>
                                <div class="layui-input-inline query-form-input">
                                    <input type="text" name="plate" id="plate" autocomplete="off" placeholder="车牌号"
                                           class="layui-input" lay-verify="plate">
                                </div>
                                <div class="layui-form-mid query-form-checkbox">
                                    <input type="checkbox" name="usePlate" id="usePlate" title="使用车牌号查询" data-target="plate">
                                </div>
                            </div>

                            <div class="query-form-item">
                                <label class="query-form-label">施工单位</label>
                                <div class="layui-input-inline query-form-input">
                                    <select name="belonging" id="belonging" lay-verify="belonging">
                                        <option value="">请选择</option>
                                        <option value="施工单位A">施工单位A</option>
                                        <option value="施工单位B">施工单位B</option>
                                        <option value="施工单位C">施工单位C</option>
                                    </select>
                                </div>
                                <div class="layui-form-mid query-form-checkbox">
                                    <input type="checkbox" name="useBelonging" id="useBelonging" title="使用施工单位查询"
                                           data-target="belonging">
                                </div>
                            </div>

                            <div class="query-form-item">
                                <label class="query-form-label">开始时间</label>
                                <div class="layui-input-inline query-form-input">
                                    <input type="text" name="startTime" id="startTime" autocomplete="off" placeholder="开始时间"
                                           class="layui-input" lay-verify="startTime">
                                </div>
                                <div class="layui-form-mid query-form-checkbox">
                                    <input type="checkbox" name="useStartTime" id="useStartTime" title="使用开始时间查询"
                                           data-target="startTime">
                                </div>
                            </div>

                            <div class="query-form-item">
                                <label class="query-form-label">结束时间</label>
                                <div class="layui-input-inline query-form-input">
                                    <input type="text" name="endTime" id="endTime" autocomplete="off" placeholder="结束时间"
                                           class="layui-input" lay-verify="endTime">
                                </div>
                                <div class="layui-form-mid query-form-checkbox">
                                    <input type="checkbox" name="useEndTime" id="useEndTime" title="使用结束时间查询"
                                           data-target="endTime">
                                </div>
                            </div>

                            <div class="query-form-item query-form-actions">
                                <button class="layui-btn" lay-submit lay-filter="form">
                                    <i class="fa fa-search"></i> 查询
                                </button>
                                <button class="layui-btn layui-btn-normal" id="exportBtn">
                                    <i class="fa fa-download"></i> 导出Excel
                                </button>
                            </div>
                        </div>

                        <table id="dataTable" lay-filter="dataTable"></table>

                        <div class="statistics-container">
                            <div class="statistics-item">
                                <i class="fa fa-balance-scale"></i>
                                <span>总重量:</span>
                                <span class="statistics-value" id="totalWeight">0.00</span>
                                <span>吨</span>
                            </div>
                            <div class="statistics-item">
                                <i class="fa fa-cubes"></i>
                                <span>总体积:</span>
                                <span class="statistics-value" id="totalVolume">0.00</span>
                                <span>立方米</span>
                            </div>
                            <div class="statistics-item">
                                <i class="fa fa-truckRecord"></i>
                                <span>总记录:</span>
                                <span class="statistics-value" id="totalCount">0</span>
                                <span>条</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 用户编辑弹窗模板 -->
<script type="text/html" id="userEditTpl">
    <form class="layui-form" lay-filter="userEditForm" style="padding:20px">
        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-block">
                <input type="text" name="username" autocomplete="off" class="layui-input" lay-verify="required">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-block">
                <input type="password" name="password" autocomplete="off" placeholder="******"
                       class="layui-input" lay-verify="${data.id ? '' : 'required'}">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">角色</label>
            <div class="layui-input-block">
                <select name="isAdmin" lay-verify="required">
                    <option value="true" {{ d.isAdmin ? 'selected' : '' }}>管理员</option>
                    <option value="false" {{ !d.isAdmin ? 'selected' : '' }}>普通用户</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">所属单位</label>
            <div class="layui-input-block">
                <select name="unitId" id="unitSelect" lay-verify="required" lay-search>
                    {{# layui.each(units, function(index, item){ }}
                    <option value="{{ item.id }}" {{ item.id == d.unitId ? 'selected' : '' }}>{{ item.unitName }}</option>
                    {{# }); }}
                </select>
            </div>
        </div>
        <input type="hidden" name="id" value="{{ d.id }}">
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit>
                    <i class="fa fa-save"></i> 提交
                </button>
                <button type="reset" class="layui-btn layui-btn-primary">
                    <i class="fa fa-refresh"></i> 重置
                </button>
            </div>
        </div>
    </form>
</script>

<!-- 数据编辑弹窗模板 -->
<script type="text/html" id="dataEditTpl">
    <form class="layui-form" lay-filter="dataEditForm" style="padding:20px">
        <div class="layui-form-item">
            <label class="layui-form-label">门岗</label>
            <div class="layui-input-block">
                <input type="text" name="gate" value="{{ d.gate }}" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">施工单位</label>
            <div class="layui-input-block">
                <input type="text" name="belonging" value="{{ d.belonging }}" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">车牌号</label>
            <div class="layui-input-block">
                <input type="text" name="plate" value="{{ d.plate }}" class="layui-input" lay-verify="plate">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">时间</label>
            <div class="layui-input-block">
                <input type="text" name="time" value="{{ d.time }}" class="layui-input" lay-verify="required">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">材料</label>
            <div class="layui-input-block">
                <input type="text" name="material" value="{{ d.material }}" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">密度</label>
            <div class="layui-input-block">
                <input type="number" name="density" value="{{ d.density }}" step="0.01" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">体积(m³)</label>
            <div class="layui-input-block">
                <input type="number" name="volume" value="{{ d.volume }}" step="0.01" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">重量(吨)</label>
            <div class="layui-input-block">
                <input type="number" name="weight" value="{{ d.weight }}" step="0.01" class="layui-input">
            </div>
        </div>
        <input type="hidden" name="id" value="{{ d.id }}">
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit>
                    <i class="fa fa-save"></i> 保存
                </button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="resetForm()">
                    <i class="fa fa-refresh"></i> 重置
                </button>
            </div>
        </div>
    </form>
</script>

<script src="../layui/layui.js"></script>
<script>
    layui.use(['element', 'table', 'form', 'layer', 'laydate'], function() {
        const $ = layui.$,
            element = layui.element,
            table = layui.table,
            form = layui.form,
            layer = layui.layer,
            laydate = layui.laydate;

        // 初始化日期选择器
        laydate.render({ elem: '#startTime', type: 'datetime' });
        laydate.render({ elem: '#endTime', type: 'datetime' });

        // 用户管理表格
        const userTable = table.render({
            elem: '#userTable',
            url: 'http://59.110.144.74/user/users',
            cols: [[
                {field: 'id', title: 'ID', width: 80},
                {field: 'username', title: '用户名', width: 150},
                {field: 'isAdmin', title: '角色', width: 120, templet: d => d.isAdmin ?
                        '<span class="layui-badge layui-bg-blue">管理员</span>' :
                        '<span class="layui-badge layui-bg-gray">普通用户</span>'
                },
                {field: 'unitId', title: '所属单位', width: 180, templet: async d => await getUnitName(d.unitId)},
                {title: '操作', width: 150, toolbar: '#userBar'}
            ]],
            page: true,
            limit: 10,
            response: {statusCode: 0},
            done: function() {
                // 表格加载完成后的回调
            }
        });

        // 数据查询表格
        const dataTable = table.render({
            elem: '#dataTable',
            url: 'http://59.110.144.74/truckRecord/truckRecords',
            cols: [[
                {field: 'id', title: '序号', width: 80},
                {field: 'uuid', title: '唯一标识', width: 180},
                {field: 'gate', title: '门岗', width: 100},
                {field: 'belonging', title: '施工单位', width: 120},
                {field: 'plate', title: '车牌号', width: 120},
                {field: 'time', title: '时间', width: 160},
                {field: 'material', title: '材料', width: 100},
                {field: 'density', title: '密度', width: 100, templet: d => (d.density || 0).toFixed(2)},
                {field: 'volume', title: '体积(m³)', width: 120, templet: d => (d.volume || 0).toFixed(2)},
                {field: 'weight', title: '重量(吨)', width: 120, templet: d => (d.weight || 0).toFixed(2)},
                {field: 'scan', title: '扫描状态', width: 100, templet: d => d.scan ?
                        '<span class="layui-badge layui-bg-green">已扫描</span>' :
                        '<span class="layui-badge layui-bg-orange">未扫描</span>'
                },
                {field: 'status', title: '同步状态', width: 100, templet: d => d.status ?
                        '<span class="layui-badge layui-bg-green">已同步</span>' :
                        '<span class="layui-badge layui-bg-orange">未同步</span>'
                },
                {title: '操作', width: 120, toolbar: '#barDemo'}
            ]],
            page: true,
            limit: 10,
            response: {statusCode: 0},
            done: res => updateStatistics(res)
        });

        // 获取单位名称
        async function getUnitName(unitId) {
            try {
                const res = await $.ajax({
                    url: `http://59.110.144.74/user/unitName/${unitId}`,
                    method: 'GET'
                });
                return res.data || '未知单位';
            } catch (error) {
                return '未知单位';
            }
        }

        // 更新统计信息
        function updateStatistics(data) {
            const totalWeight = data.totalWeight || 0;
            const totalVolume = data.totalVolume || 0;
            const totalCount = data.count || 0;

            $('#totalWeight').text(totalWeight.toFixed(2));
            $('#totalVolume').text(totalVolume.toFixed(2));
            $('#totalCount').text(totalCount);
        }

        // 初始化导航状态
        function initNav() {
            $('.layui-nav-item[data-tab="user"]')
                .addClass('layui-this')
                .siblings().removeClass('layui-this');
            element.render('nav');
        }

        // 更新当前时间
        function updateCurrentTime() {
            const now = moment().format('YYYY年MM月DD日 HH:mm:ss');
            $('#currentTime').text(now);
            $('#currentTimeMobile').text(now);
        }

        setInterval(updateCurrentTime, 1000);
        updateCurrentTime(); // 初始化一次

        // 页面加载完成后执行
        $(document).ready(function() {
            const username = sessionStorage.getItem('username');
            const unitId = sessionStorage.getItem('unitId');

            if (!username || !unitId) {
                layer.msg('请先登录', {icon: 2});
                setTimeout(() => window.location.href = 'login.html', 1500);
            } else {
                $('#usernameDisplay').text(username);
                $('#usernameDisplayMobile').text(username);
                initNav();
                element.init();
            }
        });

        // 导航栏切换事件
        $(document).on('click', '.layui-nav-item', function () {
            const $navItem = $(this);
            const tabId = $navItem.data('tab');
            if (!tabId) return;

            // 更新导航状态
            $navItem.addClass('layui-this').siblings().removeClass('layui-this');

            // 切换标签页
            setTimeout(() => {
                element.render('nav');
                element.tabChange('adminTabs', tabId);
            }, 100);
        });

        // 监听窗口变化重新渲染
        $(window).on('resize', function(){
            element.render('tab');
            element.render('nav');
        });

        // 用户管理操作
        table.on('tool(userTable)', function(obj) {
            const data = obj.data;
            if(obj.event === 'edit') {
                editUser(data);
            } else if(obj.event === 'delete') {
                layer.confirm('确定删除该用户？', {
                    icon: 3,
                    title: '确认删除'
                }, function(index) {
                    $.ajax({
                        url: `http://59.110.144.74/user/delete/${data.id}`,
                        type: 'DELETE',
                        success: () => {
                            layer.msg('删除成功', {icon: 1});
                            userTable.reload();
                        },
                        error: xhr => layer.msg('删除失败: ' + xhr.responseText, {icon: 2})
                    });
                    layer.close(index);
                });
            }
        });

        // 数据编辑操作
        table.on('tool(dataTable)', function(obj) {
            const data = obj.data;
            if(obj.event === 'edit') {
                layer.open({
                    type: 1,
                    title: '编辑数据',
                    area: ['600px', '80%'],
                    content: layui.laytpl($('#dataEditTpl').html()).render(data),
                    success: function(layero) {
                        form.render();
                    }
                });
            }
        });

        // 添加用户功能
        $('#addUserBtn').click(() => editUser({}));

        // 修改 editUser 方法
        async function editUser(data) {
            try {
                const units = await loadUnits();
                layer.open({
                    type: 1,
                    title: data.id ? '编辑用户' : '添加用户',
                    area: ['500px', '400px'],
                    content: layui.laytpl($('#userEditTpl').html()).render({
                        d: data,
                        units: units
                    }),
                    success: function(layero) {
                        form.render();
                    }
                });
            } catch (error) {
                layer.msg('初始化编辑窗口失败', {icon: 2});
            }
        }

        // 修改 loadUnits 方法为异步模式
        async function loadUnits() {
            try {
                const res = await $.ajax({
                    url: 'http://59.110.144.74/user/units',
                    method: 'GET'
                });
                return res.data || [];
            } catch (error) {
                layer.msg('单位数据加载失败', {icon: 2});
                return [];
            }
        }

        form.on('submit(userEditForm)', function(data) {
            const isEdit = !!data.field.id;
            data.field.isAdmin = data.field.isAdmin === 'true';

            $.ajax({
                url: isEdit ? 'http://59.110.144.74:8080/user/update' : 'http://59.110.144.74:8080/user/add',
                method: isEdit ? 'PUT' : 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data.field),
                success: () => {
                    layer.msg(isEdit ? '更新成功' : '添加成功');
                    userTable.reload();
                    layer.closeAll();
                },
                error: xhr => layer.msg('操作失败: ' + xhr.responseText)
            });
            return false;
        });

        form.on('submit(dataEditForm)', function(data) {
            const fields = data.field;
            fields.density = parseFloat(fields.density);
            fields.volume = parseFloat(fields.volume);
            fields.weight = parseFloat(fields.weight);

            $.ajax({
                url: 'http://59.110.144.74/truckRecord/update',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(fields),
                success: () => {
                    layer.msg('更新成功');
                    dataTable.reload();
                    layer.closeAll();
                },
                error: xhr => layer.msg('更新失败: ' + xhr.responseText)
            });
            return false;
        });

        // 数据查询表单提交
        form.on('submit(form)', function(data) {
            const queryParams = {};
            const fields = data.field;

            if(fields.useGate === 'on' && fields.gate) queryParams.gate = fields.gate;
            if(fields.usePlate === 'on' && fields.plate) queryParams.plate = fields.plate;
            if(fields.useBelonging === 'on' && fields.belonging) queryParams.belonging = fields.belonging;
            if(fields.useStartTime === 'on' && fields.startTime) queryParams.startTime = fields.startTime;
            if(fields.useEndTime === 'on' && fields.endTime) queryParams.endTime = fields.endTime;

            dataTable.reload({ where: queryParams, page: { curr: 1 } });
            return false;
        });

        // 表单验证
        form.verify({
            plate: value => {
                if($('#usePlate').is(':checked') && !/^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z0-9]{5}$/.test(value)) {
                    return '车牌号格式不正确，示例：京A12345';
                }
            },
            startTime: value => {
                if($('#useStartTime').is(':checked') && !value) return '请选择开始时间';
            },
            endTime: value => {
                const startTime = $('#startTime').val();
                if(value && startTime && moment(value).isBefore(moment(startTime))) {
                    return '结束时间不能早于开始时间';
                }
            }
        });

        // Excel导出功能
        $('#exportBtn').click(function() {
            const filename = prompt('请输入文件名', '矿车数据');
            if(filename) {
                const data = table.cache.dataTable;
                const worksheet = XLSX.utils.json_to_sheet(data);
                const workbook = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
                const excelFile = XLSX.write(workbook, {bookType: 'xlsx', type: 'array'});
                saveAs(new Blob([excelFile], {type: 'application/octet-stream'}), `${filename}.xlsx`);
            }
        });

        // 退出系统功能
        $('#logoutBtn').click(function() {
            layer.confirm('确定要退出系统吗？', {
                icon: 3,
                title: '确认退出'
            }, function(index) {
                sessionStorage.clear();
                window.location.href = 'login.html';
                layer.close(index);
            });
        });

        // 重置表单数据的函数
        function resetForm() {
            $('.layui-form-item input, .layui-form-item select').val('');
            form.render();
        }
    });
</script>

<!-- 操作列模板 -->
<script type="text/html" id="userBar">
    <a class="layui-btn layui-btn-xs table-action-btn" lay-event="edit">
        <i class="fa fa-pencil"></i> 编辑
    </a>
    <a class="layui-btn layui-btn-danger layui-btn-xs table-action-btn" lay-event="delete">
        <i class="fa fa-trash"></i> 删除
    </a>
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs table-action-btn" lay-event="edit">
        <i class="fa fa-pencil"></i> 编辑
    </a>
</script>
</body>
</html>